/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.controller.admin;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.finalist.FileInfo.FileType;
import com.finalist.Filter;
import com.finalist.Filter.Operator;
import com.finalist.Message;
import com.finalist.Pageable;
import com.finalist.ProductItemVo;
import com.finalist.ProductVo;
import com.finalist.Setting;
import com.finalist.entity.Admin;
import com.finalist.entity.AdminStory;
import com.finalist.entity.Attribute;
import com.finalist.entity.Brand;
import com.finalist.entity.Departure;
import com.finalist.entity.Destination;
import com.finalist.entity.Goods;
import com.finalist.entity.MemberRank;
import com.finalist.entity.PackageProduct;
import com.finalist.entity.Parameter;
import com.finalist.entity.ParameterGroup;
import com.finalist.entity.Product;
import com.finalist.entity.Product.OrderType;
import com.finalist.entity.Product.RecommendType;
import com.finalist.entity.ProductCategory;
import com.finalist.entity.ProductImage;
import com.finalist.entity.ProductItem;
import com.finalist.entity.Promotion;
import com.finalist.entity.Specification;
import com.finalist.entity.SpecificationValue;
import com.finalist.entity.Tag;
import com.finalist.entity.Tag.Type;
import com.finalist.service.AdminService;
import com.finalist.service.AdminStoryService;
import com.finalist.service.BrandService;
import com.finalist.service.DepartureService;
import com.finalist.service.DestinationService;
import com.finalist.service.EditorTemplateService;
import com.finalist.service.FileService;
import com.finalist.service.GoodsService;
import com.finalist.service.MemberRankService;
import com.finalist.service.PackageProductService;
import com.finalist.service.ProductCategoryService;
import com.finalist.service.ProductImageService;
import com.finalist.service.ProductItemService;
import com.finalist.service.ProductService;
import com.finalist.service.PromotionService;
import com.finalist.service.SpecificationService;
import com.finalist.service.SpecificationValueService;
import com.finalist.service.TagService;
import com.finalist.util.DateUtil;
import com.finalist.util.SettingUtils;

/**
 * Controller - 商品
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Controller("adminProductController")
@RequestMapping("/admin/product")
public class ProductController extends BaseController {

	@Resource(name = "productServiceImpl")
	private ProductService productService;
	
	@Resource(name = "productItemServiceImpl")
	private ProductItemService productItemService;
	
	@Resource(name = "productCategoryServiceImpl")
	private ProductCategoryService productCategoryService;
	@Resource(name = "goodsServiceImpl")
	private GoodsService goodsService;
	@Resource(name = "brandServiceImpl")
	private BrandService brandService;
	@Resource(name = "promotionServiceImpl")
	private PromotionService promotionService;
	@Resource(name = "tagServiceImpl")
	private TagService tagService;
	@Resource(name = "memberRankServiceImpl")
	private MemberRankService memberRankService;
	@Resource(name = "productImageServiceImpl")
	private ProductImageService productImageService;
	@Resource(name = "specificationServiceImpl")
	private SpecificationService specificationService;
	@Resource(name = "specificationValueServiceImpl")
	private SpecificationValueService specificationValueService;
	@Resource(name = "fileServiceImpl")
	private FileService fileService;
	@Resource(name = "packageProductServiceImpl")
	private PackageProductService packageProductService;
	
	@Resource(name = "adminServiceImpl")
	private AdminService adminService;
	
//	@Resource(name = "areaStandardCodeServiceImpl")
//	private AreaStandardCodeService areaStandardCodeService;
	
	@Resource(name = "departureServiceImpl")
	private DepartureService departureService;
	@Resource(name = "destinationServiceImpl")
	private DestinationService destinationService;
	
	@Resource(name = "adminStoryServiceImpl")
	private AdminStoryService adminStoryService;
	
	@Resource(name = "editorTemplateServiceImpl" )
	private EditorTemplateService editorTemplateService;
	
    private static final Log log = LogFactory.getLog(ProductController.class);

	/**
	 * 检查编号是否唯一
	 */
	@RequestMapping(value = "/check_sn", method = RequestMethod.GET)
	public @ResponseBody
	boolean checkSn(String previousSn, String sn) {
		if (StringUtils.isEmpty(sn)) {
			return false;
		}
		if (productService.snUnique(previousSn, sn)) {
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping(value = "/deleteProductItem", method = RequestMethod.GET)
	public @ResponseBody
	boolean deleteItem(Long productItemId){
		ProductItem item=productItemService.find(productItemId);
		productItemService.delete(item);
		return true;
	}
	
	@RequestMapping(value = "/saveStoryItem", method = RequestMethod.POST)
	public @ResponseBody
	boolean saveStoryItem(Product product){
		Product oldProduct = productService.find(product.getId());
		for(Iterator<AdminStory> iterator = oldProduct.getAdminStories().iterator();iterator.hasNext();){
			AdminStory adminStory = iterator.next();
			if(adminStory==null){
				iterator.remove();
				continue;
			}
			adminStory.setProduct(null);
			adminStoryService.update(adminStory);
			adminStoryService.delete(adminStory);
		}
		for(Iterator<AdminStory> iterator = product.getAdminStories().iterator();iterator.hasNext();){
			AdminStory adminStory = iterator.next();
			if(adminStory==null){
				iterator.remove();
				continue;
			}
			if(adminStory.getContent()==null&&adminStory.getTitle()==null){
				iterator.remove();
				continue;
			}
			if(adminStory!=null&&adminStory.getContent()!=null){
				adminStory.setContent1(adminStory.getContent().replaceAll("src=", "data-original="));
			}
			
		   adminStory.setProduct(oldProduct);
			
		}
		oldProduct.setAdminStories(product.getAdminStories());
		productService.update(oldProduct);
		return true;
	}
	
	@RequestMapping(value = "/saveProductItem", method = RequestMethod.POST)
	public @ResponseBody
	boolean saveProductItem(Product product){
		Product oldProduct = productService.find(product.getId());
		for (Iterator<ProductItem> iterator = oldProduct.getProductItems()
				.iterator(); iterator.hasNext();) {
			ProductItem productItem=iterator.next();
			if(productItem==null){
				iterator.remove();
				continue;
			}
			productItem.setProduct(null);
			productItemService.update(productItem);
			productItemService.delete(productItem);
		}
		
		for (Iterator<ProductItem> iterator = product.getProductItems()
				.iterator(); iterator.hasNext();) {
			ProductItem productItem=iterator.next();
			if(productItem==null){
				iterator.remove();
				continue;
			}
			if(productItem.getIntroduction()==null){
				iterator.remove();
				continue;
			}
			if(productItem!=null&&productItem.getIntroduction()!=null){
				productItem.setIntroduction1(productItem.getIntroduction().replaceAll("src=", "data-original="));
			}
			
			productItem.setProduct(oldProduct);
			
		}
		oldProduct.setProductItems(product.getProductItems());
		productService.update(oldProduct);
		return true;
	}
	
	
	@RequestMapping(value = "/findTemplate", method = RequestMethod.GET)
	public String findTemplate(Long templateId,ModelMap model){
		Product product=productService.find(templateId);
		product.setId(null);
		model.put("product", product);
		model.put("departures", departureService.findAll());
		model.put("destinations",destinationService.findAll());
		model.put("defaultBeginDate", new Date());
		model.put("defaultExpireDate", DateUtil.addDate(new Date(), 1));
		return "/admin/product/ajaxTemplate";
	}
	
	@RequestMapping(value = "/previewProduct", method = RequestMethod.GET)
	public String preViewProduct(Long productId,ModelMap model){
		Product product=productService.find(productId);
		model.put("product", product);
		return "/admin/product/previewProduct";
	}
	
	@RequestMapping(value = "/deleteStory", method = RequestMethod.GET)
	public @ResponseBody
	boolean deleteStory(Long adminStoryId){
		AdminStory item = adminStoryService.find(adminStoryId);
		adminStoryService.delete(item);
		return true;
	}
	/**
	 * 获取参数组
	 */
	@RequestMapping(value = "/parameter_groups", method = RequestMethod.GET)
	public @ResponseBody
	Set<ParameterGroup> parameterGroups(Long id) {
		ProductCategory productCategory = productCategoryService.find(id);
		return productCategory.getParameterGroups();
	}

	/**
	 * 获取顶级分类是否暂时服务商信息
	 */
	@RequestMapping(value = "/getRootTreeSPisShowTab", method = RequestMethod.GET)
	public @ResponseBody
	String getRootTreeSPisShowTab(Long productCategoryId) {
		ProductCategory productCategory = productCategoryService
				.find(productCategoryId);
		List<Long> treePaths = productCategory.getTreePaths();
		if (treePaths != null) {
			if (treePaths.size() >= 1) {
				ProductCategory productCategory2 = productCategoryService
						.find(treePaths.get(0));
				String isShow = productCategory2
						.getIsEditServiceProvidersInfo();
				if (isShow != null) {
					return isShow;
				}
			}
			if (treePaths.size() == 0) {
				return productCategory.getIsEditServiceProvidersInfo();
			}
		}
		return "no";
	}

	/**
	 * 获取属性
	 */
	@RequestMapping(value = "/attributes", method = RequestMethod.GET)
	public @ResponseBody
	Set<Attribute> attributes(Long id) {
		ProductCategory productCategory = productCategoryService.find(id);
		return productCategory.getAttributes();
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {
			model.addAttribute("productCategoryTree",
					productCategoryService.findTree());
			model.put("departures", departureService.findAll());
			model.put("destinations",destinationService.findAll());
			model.put("defaultBeginDate", new Date());
			model.put("defaultExpireDate", DateUtil.addDate(new Date(), 1));
			model.put("admin", adminService.getCurrent());
			model.put("templates", editorTemplateService.findAll());
			return "/admin/product/add";
	}

	@RequestMapping(value = "/saveAndPreview", method = RequestMethod.POST)
	public String saveAndPreview(Product product, Long productCategoryId,
			HttpServletRequest request, RedirectAttributes redirectAttributes,String[] startingDate,
			ModelMap model) {
		if(startingDate!=null){
			StringBuffer buffer=new StringBuffer();
			for(int i=0;i<startingDate.length;i++){
				buffer.append(startingDate[i]);
				if(i!=startingDate.length-1){
					buffer.append(",");
				}
			}
			product.setStartingDate(buffer.toString());
		}
		if(product.getMaxDateStr()!=null){
			product.setExpire(DateUtil.parseDate(product.getMaxDateStr()));
		}
		if(product!=null&&product.getFeeInclude()!=null){
			product.setFeeInclude1(product.getFeeInclude().replaceAll("src=", "data-original="));
		}
		
		if(product.getIsTop()!=null&&product.getIsTop()){
			product.setStickTime(new Date());
		}
		
		if(product!=null&&product.getIntroduction()!=null){
			product.setIntroduction1(product.getIntroduction().replaceAll("src=", "data-original="));
		}
		/*for (Iterator<ProductImage> iterator = product.getProductImages()
				.iterator(); iterator.hasNext();) {
			ProductImage productImage = iterator.next();
			if (productImage == null || productImage.isEmpty()) {
				iterator.remove();
				continue;
			}
			if (productImage.getFile() != null
					&& !productImage.getFile().isEmpty()) {
				if (!fileService
						.isValid(FileType.image, productImage.getFile())) {
					addFlashMessage(redirectAttributes,
							Message.error("admin.upload.invalid"));
					return "redirect:copy.jhtml";
				}
			}
		}*/
		
		for (Iterator<ProductItem> iterator = product.getProductItems()
				.iterator(); iterator.hasNext();) {
			ProductItem productItem=iterator.next();
			if(productItem==null){
				iterator.remove();
				continue;
			}
			if(productItem.getIntroduction()==null){
				iterator.remove();
				continue;
			}
			if(productItem!=null&&productItem.getIntroduction()!=null){
				productItem.setIntroduction1(productItem.getIntroduction().replaceAll("src=", "data-original="));
			}
			
			productItem.setProduct(product);
		}
		
		for(Iterator<AdminStory> iterator = product.getAdminStories().iterator();iterator.hasNext();){
			AdminStory adminStory = iterator.next();
			if(adminStory==null){
				iterator.remove();
				continue;
			}
			if(adminStory.getContent()==null&&adminStory.getTitle()==null){
				iterator.remove();
				continue;
			}
			if(adminStory!=null&&adminStory.getContent()!=null){
				adminStory.setContent1(adminStory.getContent().replaceAll("src=", "data-original="));
			}
			
			adminStory.setProduct(product);
		}
		
		product.setProductCategory(productCategoryService
				.find(productCategoryId));
		
		
		if (product.getMarketPrice() == null) {
			BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product
					.getPrice());
			product.setMarketPrice(defaultMarketPrice);
		}
		if (product.getPoint() == null) {
			long point = calculateDefaultPoint(product.getPrice());
			product.setPoint(point);
		}
		
		
		product.setFullName(null);
		product.setAllocatedStock(0);
		product.setScore(0F);
		product.setTotalScore(0L);
		product.setScoreCount(0L);
		product.setHits(0L);
		product.setWeekHits(0L);
		product.setMonthHits(0L);
		product.setSales(0L);
		product.setWeekSales(0L);
		product.setMonthSales(0L);
		product.setWeekHitsDate(new Date());
		product.setMonthHitsDate(new Date());
		product.setWeekSalesDate(new Date());
		product.setMonthSalesDate(new Date());
		product.setReviews(null);
		product.setFavoriteMembers(null);
		product.setPromotions(null);
		product.setCartItems(null);
		product.setOrderItems(null);
		product.setGiftItems(null);
		product.setProductNotifies(null);

		
		Collections.sort(product.getProductImages());
		if (product.getImage() == null && product.getThumbnail() != null) {
			product.setImage(product.getThumbnail());
		}
		
		product.setAdmin(adminService.getCurrent());
		if(product.getHoursePrice()==null){
			product.setHoursePrice(new BigDecimal(0));
		}
		if(product.getChildrenPrice()==null){
			product.setChildrenPrice(new BigDecimal(0));
		}
		
		if (!isValid(product)) {
			return ERROR_VIEW;
		}
		try {
			productService.save(product);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "redirect:previewProduct.jhtml?productId="+product.getId();

	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Product product, Long[] id1, Long[] id2, Long productCategoryId, Long brandId,
			Long[] tagIds,String[] JLProductNotJoinId, Long[] specificationIds, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		for (Iterator<ProductImage> iterator = product.getProductImages()
				.iterator(); iterator.hasNext();) {
			ProductImage productImage = iterator.next();
			if (productImage == null || productImage.isEmpty()) {
				iterator.remove();
				continue;
			}
			if (productImage.getFile() != null
					&& !productImage.getFile().isEmpty()) {
				if (!fileService
						.isValid(FileType.image, productImage.getFile())) {
					addFlashMessage(redirectAttributes,
							Message.error("admin.upload.invalid"));
					return "redirect:add.jhtml";
				}
			}
		}
		Set<PackageProduct> products1 = new HashSet<PackageProduct>();
		if (id1 != null) {
			for (int i = 0; i < id1.length; i++) {
				PackageProduct packageProduct = new PackageProduct();
				packageProduct.setProduct(product);
				packageProduct.setProducts(productService.find(id1[i]));
				products1.add(packageProduct);
			}
		}

		//Set<Product> products2 = new HashSet<Product>();
		if (id2 != null) {
			for (int i = 0; i < id2.length; i++) {
				PackageProduct packageProduct = new PackageProduct();
				packageProduct.setProduct(product);
				packageProduct.setProducts(productService.find(id2[i]));
				products1.add(packageProduct);
			}
		}
		/*product.setProducts1(products1);
		product.setProducts2(products2);*/
		product.setPackageProducts(products1);
		product.setProductCategory(productCategoryService
				.find(productCategoryId));
		product.setBrand(brandService.find(brandId));
		product.setTags(new HashSet<Tag>(tagService.findList(tagIds)));
		if (!isValid(product)) {
			return ERROR_VIEW;
		}
		if (StringUtils.isNotEmpty(product.getSn())
				&& productService.snExists(product.getSn())) {
			return ERROR_VIEW;
		}
		if (product.getMarketPrice() == null) {
			BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product
					.getPrice());
			product.setMarketPrice(defaultMarketPrice);
		}
		if (product.getPoint() == null) {
			long point = calculateDefaultPoint(product.getPrice());
			product.setPoint(point);
		}
		product.setFullName(null);
		product.setAllocatedStock(0);
		product.setScore(0F);
		product.setTotalScore(0L);
		product.setScoreCount(0L);
		product.setHits(0L);
		product.setWeekHits(0L);
		product.setMonthHits(0L);
		product.setSales(0L);
		product.setWeekSales(0L);
		product.setMonthSales(0L);
		product.setWeekHitsDate(new Date());
		product.setMonthHitsDate(new Date());
		product.setWeekSalesDate(new Date());
		product.setMonthSalesDate(new Date());
		product.setReviews(null);
		product.setFavoriteMembers(null);
		product.setPromotions(null);
		product.setCartItems(null);
		product.setOrderItems(null);
		product.setGiftItems(null);
		product.setProductNotifies(null);

		for (MemberRank memberRank : memberRankService.findAll()) {
			String price = request.getParameter("memberPrice_"
					+ memberRank.getId());
			if (StringUtils.isNotEmpty(price)
					&& new BigDecimal(price).compareTo(new BigDecimal(0)) >= 0) {
				product.getMemberPrice().put(memberRank, new BigDecimal(price));
			} else {
				product.getMemberPrice().remove(memberRank);
			}
		}

		for (ProductImage productImage : product.getProductImages()) {
			productImageService.build(productImage);
		}
		Collections.sort(product.getProductImages());
		if (product.getImage() == null && product.getThumbnail() != null) {
			product.setImage(product.getThumbnail());
		}

		for (ParameterGroup parameterGroup : product.getProductCategory()
				.getParameterGroups()) {
			for (Parameter parameter : parameterGroup.getParameters()) {
				String parameterValue = request.getParameter("parameter_"
						+ parameter.getId());
				if (StringUtils.isNotEmpty(parameterValue)) {
					product.getParameterValue().put(parameter, parameterValue);
				} else {
					product.getParameterValue().remove(parameter);
				}
			}
		}

		for (Attribute attribute : product.getProductCategory().getAttributes()) {
			String attributeValue = request.getParameter("attribute_"
					+ attribute.getId());
			if (StringUtils.isNotEmpty(attributeValue)) {
				product.setAttributeValue(attribute, attributeValue);
			} else {
				product.setAttributeValue(attribute, null);
			}
		}

		Goods goods = new Goods();
		List<Product> products = new ArrayList<Product>();
		if (specificationIds != null && specificationIds.length > 0) {
			for (int i = 0; i < specificationIds.length; i++) {
				Specification specification = specificationService
						.find(specificationIds[i]);
				String[] specificationValueIds = request
						.getParameterValues("specification_"
								+ specification.getId());
				if (specificationValueIds != null
						&& specificationValueIds.length > 0) {
					for (int j = 0; j < specificationValueIds.length; j++) {
						if (i == 0) {
							if (j == 0) {
								product.setGoods(goods);
								product.setSpecifications(new HashSet<Specification>());
								product.setSpecificationValues(new HashSet<SpecificationValue>());
								products.add(product);
							} else {
								Product specificationProduct = new Product();
								BeanUtils.copyProperties(product,
										specificationProduct);
								specificationProduct.setId(null);
								specificationProduct.setCreateDate(null);
								specificationProduct.setModifyDate(null);
								specificationProduct.setSn(null);
								specificationProduct.setFullName(null);
								specificationProduct.setAllocatedStock(0);
								specificationProduct.setIsList(false);
								specificationProduct.setScore(0F);
								specificationProduct.setTotalScore(0L);
								specificationProduct.setScoreCount(0L);
								specificationProduct.setHits(0L);
								specificationProduct.setWeekHits(0L);
								specificationProduct.setMonthHits(0L);
								specificationProduct.setSales(0L);
								specificationProduct.setWeekSales(0L);
								specificationProduct.setMonthSales(0L);
								specificationProduct
										.setWeekHitsDate(new Date());
								specificationProduct
										.setMonthHitsDate(new Date());
								specificationProduct
										.setWeekSalesDate(new Date());
								specificationProduct
										.setMonthSalesDate(new Date());
								specificationProduct.setGoods(goods);
								specificationProduct.setReviews(null);
								specificationProduct.setFavoriteMembers(null);
								specificationProduct
										.setSpecifications(new HashSet<Specification>());
								specificationProduct
										.setSpecificationValues(new HashSet<SpecificationValue>());
								specificationProduct.setPromotions(null);
								specificationProduct.setCartItems(null);
								specificationProduct.setOrderItems(null);
								specificationProduct.setGiftItems(null);
								specificationProduct.setProductNotifies(null);
								
								specificationProduct.setProductIdErp(null);
								specificationProduct.setExternalId(null);
								specificationProduct.setHealthErpId(null);
								specificationProduct.setModifyDateErp(null);
								specificationProduct.setFbarcodeErp(null);
								specificationProduct.setIsJLProduct(false);
								// 将新增商品和金立商品合并
								for (int m = 0; m < JLProductNotJoinId.length; m++) {
									if(m + 1 == j) {
										String fullStr = JLProductNotJoinId[m];
										if (fullStr != null && !fullStr.equals("")) {
											String jlPro = fullStr;
											Long jlProId = Long.parseLong(jlPro.toString());
											Product jLProduct = productService.find(jlProId);
											if (jLProduct != null) {
												specificationProduct.setProductIdErp(jLProduct.getProductIdErp());
												specificationProduct.setExternalId(jLProduct.getExternalId());
												specificationProduct.setHealthErpId(jLProduct.getHealthErpId());
												specificationProduct.setModifyDateErp(jLProduct.getModifyDateErp());
												specificationProduct.setFbarcodeErp(jLProduct.getFbarcodeErp());
												specificationProduct.setIsJoin(true);
												specificationProduct.setIsJLProduct(true);
												specificationProduct.setName(jLProduct.getName());
												productService.delete(jLProduct);
											}
										}
									}
								}
								products.add(specificationProduct);
							}
						}
						Product specificationProduct = products.get(j);
						SpecificationValue specificationValue = specificationValueService
								.find(Long.valueOf(specificationValueIds[j]));
						specificationProduct.getSpecifications().add(
								specification);
						specificationProduct.getSpecificationValues().add(
								specificationValue);
						if (specificationValue.getSpecifcationValueCode() != null) {
							if (specificationValue.getSpecifcationValueCode()
									.equals("0YuanPurchase")) {// 0元购机
								specificationProduct
										.setTypeOfPurchase("0YuanPurchase");
								specificationProduct.setHas_agreement(true);
							} else if (specificationValue
									.getSpecifcationValueCode().equals(
											"purchaseDeliveryFee")) { // 购机送费
								specificationProduct
										.setTypeOfPurchase("purchaseDeliveryFee");
								specificationProduct.setHas_agreement(true);
							} else if (specificationValue
									.getSpecifcationValueCode().equals(
											"buyTheBare")) { // 购买裸机
								specificationProduct
										.setTypeOfPurchase("buyTheBare");
								specificationProduct.setHas_agreement(false);
							} else {
								specificationProduct.setTypeOfPurchase(null);
								specificationProduct.setHas_agreement(false);
							}
						}
					}
				}
			}
		} else {
			product.setGoods(goods);
			product.setSpecifications(null);
			product.setSpecificationValues(null);
			products.add(product);
		}
		goods.getProducts().clear();
		goods.getProducts().addAll(products);
		goodsService.save(goods);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}
	
	
	/**
	 * 保存
	 */
	@RequestMapping(value = "/saveAjax",method = RequestMethod.POST)
	@ResponseBody
	public String saveAjax(Product product, Long productCategoryId,
			HttpServletRequest request, RedirectAttributes redirectAttributes,String[] startingDate,
			ModelMap model) {
		
		if(startingDate!=null){
			StringBuffer buffer=new StringBuffer();
			for(int i=0;i<startingDate.length;i++){
				buffer.append(startingDate[i]);
				if(i!=startingDate.length-1){
					buffer.append(",");
				}
			}
			product.setStartingDate(buffer.toString());
		}
		if(product.getMaxDateStr()!=null){
			product.setExpire(DateUtil.parseDate(product.getMaxDateStr()));
		}
		
		if(product.getIsTop()!=null&&product.getIsTop()){
			product.setStickTime(new Date());
		}
		
		if(product!=null&&product.getFeeInclude()!=null){
			product.setFeeInclude1(product.getFeeInclude().replaceAll("src=", "data-original="));
		}
		
		if(product!=null&&product.getIntroduction()!=null){
			product.setIntroduction1(product.getIntroduction().replaceAll("src=", "data-original="));
		}
		
		product.setProductCategory(productCategoryService
				.find(productCategoryId));
		
		
		if (product.getMarketPrice() == null) {
			BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product
					.getPrice());
			product.setMarketPrice(defaultMarketPrice);
		}
		if (product.getPoint() == null) {
			long point = calculateDefaultPoint(product.getPrice());
			product.setPoint(point);
		}
		
		product.setFullName(null);
		product.setAllocatedStock(0);
		product.setScore(0F);
		product.setTotalScore(0L);
		product.setScoreCount(0L);
		product.setHits(0L);
		product.setWeekHits(0L);
		product.setMonthHits(0L);
		product.setSales(0L);
		product.setWeekSales(0L);
		product.setMonthSales(0L);
		product.setWeekHitsDate(new Date());
		product.setMonthHitsDate(new Date());
		product.setWeekSalesDate(new Date());
		product.setMonthSalesDate(new Date());
		product.setReviews(null);
		product.setFavoriteMembers(null);
		product.setPromotions(null);
		product.setCartItems(null);
		product.setOrderItems(null);
		product.setGiftItems(null);
		product.setProductNotifies(null);
		
		if(product.getHoursePrice()==null){
			product.setHoursePrice(new BigDecimal(0));
		}
		
		if(product.getChildrenPrice()==null){
			product.setChildrenPrice(new BigDecimal(0));
		}
		
		if (product.getImage() == null && product.getThumbnail() != null) {
			product.setImage(product.getThumbnail());
		}
		
		product.setAdmin(adminService.getCurrent());
		
		if (!isValid(product)) {
			log.error("product object invalid saveAjax");
			return "productInvalid";
		}
		
		productService.save(product);
		return product.getId()+"";
	}
	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, String saveAndPreview, ModelMap model) {
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
//		model.addAttribute("brands", brandService.findAll());
//		model.addAttribute("tags", tagService.findList(Type.product));
//		model.addAttribute("memberRanks", memberRankService.findAll());
//		model.addAttribute("recommendTypes", RecommendType.values());
//		model.addAttribute("phoneTypes", PhoneType.values());
//		model.addAttribute("specifications", specificationService.findAll());
		model.put("templates", editorTemplateService.findAll());
		model.put("defaultExpireDate", DateUtil.addDate(new Date(), 1));
		Product product = productService.find(id);
		model.addAttribute("product", product);
		
//		model.put("areas", areaStandardCodeService.findAll());
		model.put("departures", departureService.findAll());
		model.put("destinations",destinationService.findAll());
		model.put("admin", adminService.getCurrent());
		if (product!=null && product.getPackageProducts()!=null) {
			/*List<Product> products1 = new ArrayList<Product>();
			List<Product> products2 = new ArrayList<Product>();
			for (PackageProduct packageProduct : product.getPackageProducts()) {  
			      if (packageProduct.getCategory().equals(PackageProduct.Category.miaoShop)) {
			    	  products1.add(product);
			      }
			      if (packageProduct.getCategory().equals(PackageProduct.Category.weixinShop)) {
			    	  products2.add(product);
			      }
			}*/  
			model.addAttribute("products1", product.getPackageProducts());
			model.addAttribute("products2", product.getPackageProducts());
		}
		
		model.addAttribute("saveAndPreview", saveAndPreview);
		model.put("defaultBeginDate", new Date());
		return "/admin/product/edit";
	}

	/**
	 * 确定并发布 
	 */
	@RequestMapping(value = "/confirmOrPublish", method = RequestMethod.POST)
	public String confirmOrPublish(Product product, Long productCategoryId,  BigDecimal[] miaoPreferentialPrices, BigDecimal[] weiXinPreferentialPrices, Long[] id1, Long[] id2, Long brandId,String[] JLProductNotJoinId, Long[] tagIds, Long[] specificationIds,
			Long[] specificationProductIds, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		
			Product oldProduct = productService.find(product.getId());
		
		Set<PackageProduct> products1 =  oldProduct.getPackageProducts();
		Set<PackageProduct> products2 =  new HashSet<PackageProduct>();
		for (PackageProduct pp : products1) {  
			packageProductService.delete(pp);
		} 
		if (id1 != null) {
			for (int i = 0; i < id1.length; i++) {
					PackageProduct packageProduct = new PackageProduct();
					packageProduct.setProduct(oldProduct);
					packageProduct.setCategory(PackageProduct.Category.miaoShop);
					if (miaoPreferentialPrices!=null  && miaoPreferentialPrices.length >=i ) {
						packageProduct.setPreferentialPrice(miaoPreferentialPrices[i]);
					}
					packageProduct.setProducts(productService.find(id1[i]));
					packageProductService.save(packageProduct);
					products2.add(packageProduct);
			}
		}

		
		if (id2 != null) {
			for (int i = 0; i < id2.length; i++) {
					PackageProduct packageProduct = new PackageProduct();
					packageProduct.setProduct(oldProduct);
					packageProduct.setCategory(PackageProduct.Category.weixinShop);
					if (weiXinPreferentialPrices!=null && weiXinPreferentialPrices.length >=i ) {
						packageProduct.setPreferentialPrice(weiXinPreferentialPrices[i]);
					}
					packageProduct.setProducts(productService.find(id2[i]));
					packageProductService.save(packageProduct);
					products2.add(packageProduct);
			}
		}
		oldProduct.setPackageProducts(products2);
		productService.update(oldProduct);
		
		for (Iterator<ProductImage> iterator = product.getProductImages()
				.iterator(); iterator.hasNext();) {
			ProductImage productImage = iterator.next();
			if (productImage == null || productImage.isEmpty()) {
				iterator.remove();
				continue;
			}
			if (productImage.getFile() != null
					&& !productImage.getFile().isEmpty()) {
				if (!fileService
						.isValid(FileType.image, productImage.getFile())) {
					addFlashMessage(redirectAttributes,
							Message.error("admin.upload.invalid"));
					return "redirect:edit.jhtml?id=" + product.getId();
				}
			}
		}
		
		product.setProductCategory(productCategoryService
				.find(productCategoryId));
		product.setBrand(brandService.find(brandId));
		product.setTags(new HashSet<Tag>(tagService.findList(tagIds)));
		if (!isValid(product)) {
			return ERROR_VIEW;
		}
		Product pProduct = productService.find(product.getId());
		if (pProduct == null) {
			return ERROR_VIEW;
		}
		if (StringUtils.isNotEmpty(product.getSn())
				&& !productService.snUnique(pProduct.getSn(), product.getSn())) {
			return ERROR_VIEW;
		}
		if (product.getMarketPrice() == null) {
			BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product
					.getPrice());
			product.setMarketPrice(defaultMarketPrice);
		}
		if (product.getPoint() == null) {
			long point = calculateDefaultPoint(product.getPrice());
			product.setPoint(point);
		}
		if (product.getIsList() == false) {
			product.setIsList(true);
		}
		for (MemberRank memberRank : memberRankService.findAll()) {
			String price = request.getParameter("memberPrice_"
					+ memberRank.getId());
			if (StringUtils.isNotEmpty(price)
					&& new BigDecimal(price).compareTo(new BigDecimal(0)) >= 0) {
				product.getMemberPrice().put(memberRank, new BigDecimal(price));
			} else {
				product.getMemberPrice().remove(memberRank);
			}
		}

		for (ProductImage productImage : product.getProductImages()) {
			productImageService.build(productImage);
		}
		Collections.sort(product.getProductImages());
		if (product.getImage() == null && product.getThumbnail() != null) {
			product.setImage(product.getThumbnail());
		}

		for (ParameterGroup parameterGroup : product.getProductCategory()
				.getParameterGroups()) {
			for (Parameter parameter : parameterGroup.getParameters()) {
				String parameterValue = request.getParameter("parameter_"
						+ parameter.getId());
				if (StringUtils.isNotEmpty(parameterValue)) {
					product.getParameterValue().put(parameter, parameterValue);
				} else {
					product.getParameterValue().remove(parameter);
				}
			}
		}

		for (Attribute attribute : product.getProductCategory().getAttributes()) {
			String attributeValue = request.getParameter("attribute_"
					+ attribute.getId());
			if (StringUtils.isNotEmpty(attributeValue)) {
				product.setAttributeValue(attribute, attributeValue);
			} else {
				product.setAttributeValue(attribute, null);
			}
		}

		Goods goods = pProduct.getGoods();
		List<Product> products = new ArrayList<Product>();
		if (specificationIds != null && specificationIds.length > 0) {
			for (int i = 0; i < specificationIds.length; i++) {
				Specification specification = specificationService
						.find(specificationIds[i]);
				String[] specificationValueIds = request
						.getParameterValues("specification_"
								+ specification.getId());
				if (specificationValueIds != null
						&& specificationValueIds.length > 0) {
					for (int j = 0; j < specificationValueIds.length; j++) {
						if (i == 0) {
							if (j == 0) {
								BeanUtils.copyProperties(product, pProduct,
										new String[] { "id", "createDate",
												"modifyDate", "fullName",
												"allocatedStock", "score",
												"totalScore", "scoreCount",
												"hits", "weekHits",
												"monthHits", "sales",
												"weekSales", "monthSales",
												"weekHitsDate",
												"monthHitsDate",
												"weekSalesDate",
												"monthSalesDate", "goods",
												"reviews", "consultations",
												"favoriteMembers",
												"specifications",
												"specificationValues",
												"promotions", "cartItems",
												"orderItems", "giftItems",
												"productNotifies" });
								pProduct.setSpecifications(new HashSet<Specification>());
								pProduct.setSpecificationValues(new HashSet<SpecificationValue>());
								pProduct.setProductIdErp(product.getProductIdErp());
								pProduct.setExternalId(product.getExternalId());
								pProduct.setHealthErpId(product.getHealthErpId());
								pProduct.setFbarcodeErp(product.getFbarcodeErp());
								pProduct.setModifyDateErp(product.getModifyDateErp());
								pProduct.setIsJLProduct(product.getIsJLProduct());
								pProduct.setIsJoin(product.getIsJoin());
								products.add(pProduct);
							} else {
								if (specificationProductIds != null && j < specificationProductIds.length) {
									Product specificationProduct = productService.find(specificationProductIds[j]);
									if (specificationProduct == null
											|| (specificationProduct.getGoods() != null && !specificationProduct
													.getGoods().equals(goods))) {
										return ERROR_VIEW;
									}
									specificationProduct
											.setSpecifications(new HashSet<Specification>());
									specificationProduct
											.setSpecificationValues(new HashSet<SpecificationValue>());
									
									specificationProduct.setIsJLProduct(specificationProduct.getIsJLProduct());
									specificationProduct.setIsJoin(specificationProduct.getIsJoin());
									specificationProduct.setProductIdErp(specificationProduct.getProductIdErp());
									specificationProduct.setExternalId(specificationProduct.getExternalId());
									specificationProduct.setHealthErpId(specificationProduct.getHealthErpId());
									specificationProduct.setModifyDateErp(specificationProduct.getModifyDateErp());
									specificationProduct.setFbarcodeErp(specificationProduct.getFbarcodeErp());
									// 将新增商品和金立商品合并
									for (int m = 0; m < JLProductNotJoinId.length; m++) {
										if(m + 1 == j) {
											String fullStr = JLProductNotJoinId[m];
											if (fullStr != null
													&& !fullStr.equals("")) {
												//String[] strlist = fullStr.split(",");
												String jlPro = fullStr;
												Long jlProId = Long.parseLong(jlPro.toString());
												Product jLProduct = productService.find(jlProId);
												if (jLProduct != null) {
													specificationProduct.setProductIdErp(jLProduct.getProductIdErp());
													specificationProduct.setExternalId(specificationProduct.getExternalId());
													specificationProduct.setHealthErpId(specificationProduct.getHealthErpId());
													specificationProduct.setModifyDateErp(jLProduct.getModifyDateErp());
													specificationProduct.setFbarcodeErp(jLProduct.getFbarcodeErp());
													specificationProduct.setIsJoin(true);
													specificationProduct.setIsJLProduct(true);
													specificationProduct.setName(jLProduct.getName());
													productService.delete(jLProduct);
												}
											}
										}
									}
									
									products.add(specificationProduct);
								} else {
									Product specificationProduct = new Product();
									BeanUtils.copyProperties(product,
											specificationProduct);
									specificationProduct.setId(null);
									specificationProduct.setCreateDate(null);
									specificationProduct.setModifyDate(null);
									specificationProduct.setSn(null);
									specificationProduct.setFullName(null);
									specificationProduct.setAllocatedStock(0);
									specificationProduct.setIsList(false);
									specificationProduct.setScore(0F);
									specificationProduct.setTotalScore(0L);
									specificationProduct.setScoreCount(0L);
									specificationProduct.setHits(0L);
									specificationProduct.setWeekHits(0L);
									specificationProduct.setMonthHits(0L);
									specificationProduct.setSales(0L);
									specificationProduct.setWeekSales(0L);
									specificationProduct.setMonthSales(0L);
									specificationProduct
											.setWeekHitsDate(new Date());
									specificationProduct
											.setMonthHitsDate(new Date());
									specificationProduct
											.setWeekSalesDate(new Date());
									specificationProduct
											.setMonthSalesDate(new Date());
									specificationProduct.setGoods(goods);
									specificationProduct.setReviews(null);
									specificationProduct
											.setFavoriteMembers(null);
									specificationProduct
											.setSpecifications(new HashSet<Specification>());
									specificationProduct
											.setSpecificationValues(new HashSet<SpecificationValue>());
									specificationProduct.setPromotions(null);
									specificationProduct.setCartItems(null);
									specificationProduct.setOrderItems(null);
									specificationProduct.setGiftItems(null);
									specificationProduct.setProductNotifies(null);
									
									specificationProduct.setProductIdErp(null);
									specificationProduct.setExternalId(null);
									specificationProduct.setHealthErpId(null);
									specificationProduct.setModifyDateErp(null);
									specificationProduct.setFbarcodeErp(null);
									specificationProduct.setIsJLProduct(false);
									// 将新增商品和金立商品合并
									for (int m = 0; m < JLProductNotJoinId.length; m++) {
										if(m + 1 == j) {
											String fullStr = JLProductNotJoinId[m];
											if (fullStr != null && !fullStr.equals("")) {
												String jlPro = fullStr;
												Long jlProId = Long.parseLong(jlPro.toString());
												Product jLProduct = productService.find(jlProId);
												if (jLProduct != null) {
													specificationProduct.setProductIdErp(jLProduct.getProductIdErp());
													specificationProduct.setExternalId(jLProduct.getExternalId());
													specificationProduct.setHealthErpId(jLProduct.getHealthErpId());
													specificationProduct.setModifyDateErp(jLProduct.getModifyDateErp());
													specificationProduct.setFbarcodeErp(jLProduct.getFbarcodeErp());
													specificationProduct.setIsJoin(true);
													specificationProduct.setIsJLProduct(true);
													specificationProduct.setName(jLProduct.getName());
													productService.delete(jLProduct);
												}
											}
										}
									}
									
									products.add(specificationProduct);
								}
							}
						}
						Product specificationProduct = products.get(j);
						SpecificationValue specificationValue = specificationValueService
								.find(Long.valueOf(specificationValueIds[j]));
						specificationProduct.getSpecifications().add(
								specification);
						specificationProduct.getSpecificationValues().add(
								specificationValue);

						if (specificationValue.getSpecifcationValueCode() != null) {
							if (specificationValue.getSpecifcationValueCode()
									.equals("0YuanPurchase")) {// 0元购机
								specificationProduct
										.setTypeOfPurchase("0YuanPurchase");
								specificationProduct.setHas_agreement(true);
							} else if (specificationValue
									.getSpecifcationValueCode().equals(
											"purchaseDeliveryFee")) { // 购机送费
								specificationProduct
										.setTypeOfPurchase("purchaseDeliveryFee");
								specificationProduct.setHas_agreement(true);
							} else if (specificationValue
									.getSpecifcationValueCode().equals(
											"buyTheBare")) { // 购买裸机
								specificationProduct
										.setTypeOfPurchase("buyTheBare");
								specificationProduct.setHas_agreement(false);
							} else {
								specificationProduct.setTypeOfPurchase(null);
								specificationProduct.setHas_agreement(false);
							}
						}
					}
				}
			}
		} else {
			product.setSpecifications(null);
			product.setSpecificationValues(null);
			BeanUtils.copyProperties(product, pProduct, new String[] { "id",
					"createDate", "modifyDate", "fullName", "allocatedStock",
					"score", "totalScore", "scoreCount", "hits", "weekHits",
					"monthHits", "sales", "weekSales", "monthSales",
					"weekHitsDate", "monthHitsDate", "weekSalesDate",
					"monthSalesDate", "goods", "reviews", "consultations",
					"favoriteMembers", "promotions", "cartItems", "orderItems",
					"giftItems", "productNotifies"});
			products.add(pProduct);
		}
		goods.getProducts().clear();
		goods.getProducts().addAll(products);
		goodsService.update(goods);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Product product, Long productCategoryId,
			HttpServletRequest request, RedirectAttributes redirectAttributes,String[] startingDate) {
			Collections.sort(product.getProductImages());
			if (product.getImage() == null && product.getThumbnail() != null) {
				product.setImage(product.getThumbnail());
			}
			
			
			Product oldProduct = productService.find(product.getId());
			
			if(product!=null&&product.getFeeInclude()!=null){
				oldProduct.setFeeInclude1(product.getFeeInclude().replaceAll("src=", "data-original="));
			}
			
			if(product!=null&&product.getIntroduction()!=null){
				oldProduct.setIntroduction1(product.getIntroduction().replaceAll("src=", "data-original="));
			}
			
			for (Iterator<ProductItem> iterator = oldProduct.getProductItems()
					.iterator(); iterator.hasNext();) {
				ProductItem productItem=iterator.next();
				if(productItem==null){
					iterator.remove();
					continue;
				}
				productItem.setProduct(null);
				productItemService.update(productItem);
				productItemService.delete(productItem);
			}
			
			for(Iterator<AdminStory> iterator = oldProduct.getAdminStories().iterator();iterator.hasNext();){
				AdminStory adminStory = iterator.next();
				if(adminStory==null){
					iterator.remove();
					continue;
				}
				adminStory.setProduct(null);
				adminStoryService.update(adminStory);
				adminStoryService.delete(adminStory);
			}
			
			oldProduct.setProductFeatures(product.getProductFeatures());
			oldProduct.setName(product.getName());
			oldProduct.setPrice(product.getPrice());
			oldProduct.setChildrenPrice(product.getChildrenPrice());
			oldProduct.setHoursePrice(product.getHoursePrice());
			oldProduct.setPhone(product.getPhone());
			oldProduct.setDestination(product.getDestination());
			oldProduct.setStartAddress(product.getStartAddress());
			oldProduct.setExpire(product.getExpire());
			oldProduct.setImage(product.getImage());
			oldProduct.setServiceProvider(product.getServiceProvider());
			oldProduct.setIsTop(product.getIsTop());
			oldProduct.setIsMarketable(product.getIsMarketable());
			
			oldProduct.setIntroduction(product.getIntroduction());
			
			
			oldProduct.setFeeInclude(product.getFeeInclude());
			
			if (product.getMarketPrice() == null) {
				BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product
						.getPrice());
				oldProduct.setMarketPrice(defaultMarketPrice);
			}
			
			if (product.getPoint() == null) {
				long point = calculateDefaultPoint(product.getPrice());
				oldProduct.setPoint(point);
			}
			
			if(startingDate!=null){
				StringBuffer buffer=new StringBuffer();
				for(int i=0;i<startingDate.length;i++){
					buffer.append(startingDate[i]);
					if(i!=startingDate.length-1){
						buffer.append(",");
					}
				}
				oldProduct.setStartingDate(buffer.toString());
			}
			
			if(oldProduct.getMaxDateStr()!=null){
				oldProduct.setExpire(DateUtil.parseDate(oldProduct.getMaxDateStr()));
			}
			
			if(product.getIsTop()!=null&&product.getIsTop()){
				oldProduct.setStickTime(new Date());
			}
			
			for (Iterator<ProductItem> iterator = product.getProductItems()
					.iterator(); iterator.hasNext();) {
				ProductItem productItem=iterator.next();
				if(productItem==null){
					iterator.remove();
					continue;
				}
				if(productItem.getIntroduction()==null){
					iterator.remove();
					continue;
				}
				if(productItem!=null&&productItem.getIntroduction()!=null){
					System.out.println(productItem.getIntroduction().replaceAll("src=", "data-original="));
					productItem.setIntroduction1(productItem.getIntroduction().replaceAll("src=", "data-original="));
				}
				if(productItem.getId()==null){
					productItem.setProduct(oldProduct);
				}
			}
			
			oldProduct.setProductItems(product.getProductItems());
			
			for(Iterator<AdminStory> iterator = product.getAdminStories().iterator();iterator.hasNext();){
				AdminStory adminStory = iterator.next();
				if(adminStory==null){
					iterator.remove();
					continue;
				}
				if(adminStory.getContent()==null&&adminStory.getTitle()==null){
					iterator.remove();
					continue;
				}
				if(adminStory!=null&&adminStory.getContent()!=null){
					adminStory.setContent1(adminStory.getContent().replaceAll("src=", "data-original="));
				}
				if(adminStory.getId()==null){
					adminStory.setProduct(oldProduct);
				}
			}
			oldProduct.setAdminStories(product.getAdminStories());
			
			oldProduct.setProductCategory(productCategoryService
					.find(productCategoryId));
			
			/*for (Iterator<ProductImage> iterator = product.getProductImages()
					.iterator(); iterator.hasNext();) {
				ProductImage productImage = iterator.next();
				if (productImage == null || productImage.isEmpty()) {
					iterator.remove();
					continue;
				}
				if (productImage.getFile() != null
						&& !productImage.getFile().isEmpty()) {
					if (!fileService
							.isValid(FileType.image, productImage.getFile())) {
						addFlashMessage(redirectAttributes,
								Message.error("admin.upload.invalid"));
						return "redirect:edit.jhtml?id=" + product.getId();
					}
				}
				productImageService.build(productImage);
			}*/
			
			if(product.getHoursePrice()==null){
				oldProduct.setHoursePrice(new BigDecimal(0));
			}
			
			if(product.getChildrenPrice()==null){
				oldProduct.setChildrenPrice(new BigDecimal(0));
			}
			
			oldProduct.setProductImages(product.getProductImages());
			
			if (!isValid(oldProduct)) {
				return ERROR_VIEW;
			}

		try {
			productService.update(oldProduct);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return "redirect:previewProduct.jhtml?productId="+oldProduct.getId();
	}
	
	@RequestMapping(value = "/updateAjax", method = RequestMethod.POST)
	@ResponseBody
	public String updateAjax(Product product, Long productCategoryId,
			HttpServletRequest request, RedirectAttributes redirectAttributes,String[] startingDate) {
			if (product.getImage() == null && product.getThumbnail() != null) {
				product.setImage(product.getThumbnail());
			}
			
			Product oldProduct = productService.find(product.getId());
			/*for (Iterator<ProductImage> iterator = product.getProductImages()
					.iterator(); iterator.hasNext();) {
				ProductImage productImage = iterator.next();
				if (productImage == null || productImage.isEmpty()) {
					iterator.remove();
					continue;
				}
				if (productImage.getFile() != null
						&& !productImage.getFile().isEmpty()) {
					if (!fileService
							.isValid(FileType.image, productImage.getFile())) {
						addFlashMessage(redirectAttributes,
								Message.error("admin.upload.invalid"));
						return "imageInvalid";
					}
				}
				productImageService.build(productImage);
			}*/
			
			oldProduct.setProductImages(product.getProductImages());
			
			if(product!=null&&product.getFeeInclude()!=null){
				oldProduct.setFeeInclude1(product.getFeeInclude().replaceAll("src=", "data-original="));
			}
			
			if(product!=null&&product.getIntroduction()!=null){
				oldProduct.setIntroduction1(product.getIntroduction().replaceAll("src=", "data-original="));
			}
			
			oldProduct.setProductFeatures(product.getProductFeatures());
			oldProduct.setName(product.getName());
			oldProduct.setPrice(product.getPrice());
			oldProduct.setChildrenPrice(product.getChildrenPrice());
			oldProduct.setHoursePrice(product.getHoursePrice());
			oldProduct.setPhone(product.getPhone());
			oldProduct.setDestination(product.getDestination());
			oldProduct.setStartAddress(product.getStartAddress());
			oldProduct.setExpire(product.getExpire());
			oldProduct.setImage(product.getImage());
			oldProduct.setServiceProvider(product.getServiceProvider());
			oldProduct.setIsTop(product.getIsTop());
			oldProduct.setIsMarketable(product.getIsMarketable());
			oldProduct.setIsConfirm(product.getIsConfirm());
			oldProduct.setIntroduction(product.getIntroduction());
			
			
			oldProduct.setFeeInclude(product.getFeeInclude());
			
			if (product.getMarketPrice() == null) {
				BigDecimal defaultMarketPrice = calculateDefaultMarketPrice(product
						.getPrice());
				oldProduct.setMarketPrice(defaultMarketPrice);
			}
			
			if (product.getPoint() == null) {
				long point = calculateDefaultPoint(product.getPrice());
				oldProduct.setPoint(point);
			}
			
			if(startingDate!=null){
				StringBuffer buffer=new StringBuffer();
				for(int i=0;i<startingDate.length;i++){
					buffer.append(startingDate[i]);
					if(i!=startingDate.length-1){
						buffer.append(",");
					}
				}
				oldProduct.setStartingDate(buffer.toString());
			}
			if(oldProduct.getMaxDateStr()!=null){
				oldProduct.setExpire(DateUtil.parseDate(oldProduct.getMaxDateStr()));
			}
			
			if(product.getIsTop()!=null&&product.getIsTop()){
				oldProduct.setStickTime(new Date());
			}
			
			oldProduct.setProductCategory(productCategoryService
					.find(productCategoryId));
			
			if(product.getHoursePrice()==null){
				oldProduct.setHoursePrice(new BigDecimal(0));
			}
			
			if(product.getChildrenPrice()==null){
				oldProduct.setChildrenPrice(new BigDecimal(0));
			}
			
			if (!isValid(oldProduct)) {
				return "productInvalid";
			}

			try {
				productService.update(oldProduct);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return oldProduct.getId()+"";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Long productCategoryId, Long brandId, Long promotionId,
			Long tagId, Boolean isMarketable, Boolean isList, Boolean isTop,
			Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
			Pageable pageable, ModelMap model) {
		ProductCategory productCategory = productCategoryService
				.find(productCategoryId);
		Brand brand = brandService.find(brandId);
		Promotion promotion = promotionService.find(promotionId);
		List<Tag> tags = tagService.findList(tagId);
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("promotions", promotionService.findAll());
		model.addAttribute("tags", tagService.findList(Type.product));
		model.addAttribute("productCategoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("promotionId", promotionId);
		model.addAttribute("tagId", tagId);
		model.addAttribute("isMarketable", isMarketable);
		model.addAttribute("isList", isList);
		model.addAttribute("isTop", isTop);
		model.addAttribute("isGift", isGift);
		model.addAttribute("isOutOfStock", isOutOfStock);
		model.addAttribute("isStockAlert", isStockAlert);
		Admin admin=adminService.getCurrent();
		
		if(admin.getAminId()!=null){
			List<Filter> filters = new ArrayList<Filter>();
			Filter filter=new Filter();
			filter.setOperator(Operator.eq);
			filter.setProperty("admin");
			filter.setValue(adminService.getCurrent());
			filters.add(filter);
			pageable.setFilters(filters);
		}
		
		try {
			model.addAttribute("page", productService.findPage(productCategory,
					brand, promotion, tags, null, null, null, isMarketable, isList,
					isTop, isGift, isOutOfStock, isStockAlert, OrderType.dateDesc,
					pageable));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.put("admin", adminService.getCurrent());
		return "/admin/product/list";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Message delete(Long[] ids) {
		productService.delete(ids);
		return SUCCESS_MESSAGE;
	}


	/**
	 * 计算默认市场价
	 * 
	 * @param price
	 *            价格
	 */
	private BigDecimal calculateDefaultMarketPrice(BigDecimal price) {
		Setting setting = SettingUtils.get();
		Double defaultMarketPriceScale = setting.getDefaultMarketPriceScale();
		return setting.setScale(price.multiply(new BigDecimal(
				defaultMarketPriceScale.toString())));
	}

	/**
	 * 计算默认积分
	 * 
	 * @param price
	 *            价格
	 */
	private long calculateDefaultPoint(BigDecimal price) {
		Setting setting = SettingUtils.get();
		Double defaultPointScale = setting.getDefaultPointScale();
		return price.multiply(new BigDecimal(defaultPointScale.toString()))
				.longValue();
	}

	/**
	 * 关联查询
	 */
	@RequestMapping(value = "/connectionList", method = RequestMethod.GET)
	public String selectProductDialog(String type, Long conId, Long id,
			Long productCategoryId, Long brandId, Long promotionId, Long tagId,
			Boolean isMarketable, Boolean isList, Boolean isTop,
			Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
			Boolean isWei, Boolean isApp, Boolean isJLProduct, Boolean isJoin,
			Boolean isMiao, Pageable pageable, ModelMap model) {
		isJLProduct = true;
		isJoin = false;
		ProductCategory productCategory = productCategoryService
				.find(productCategoryId);
		Brand brand = brandService.find(brandId);
		Promotion promotion = promotionService.find(promotionId);
		List<Tag> tags = tagService.findList(tagId);
		model.addAttribute("type", type);
		model.addAttribute("id", id);
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("promotions", promotionService.findAll());
		model.addAttribute("tags", tagService.findList(Type.product));
		model.addAttribute("productCategoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("promotionId", promotionId);
		model.addAttribute("tagId", tagId);
		model.addAttribute("isMarketable", isMarketable);
		model.addAttribute("isList", isList);
		model.addAttribute("isTop", isTop);
		model.addAttribute("isGift", isGift);
		model.addAttribute("isOutOfStock", isOutOfStock);
		model.addAttribute("conId", conId);
		model.addAttribute("isStockAlert", isStockAlert);
		RecommendType recommendType1 = new Product().getRecommendType();
		if (type != null && type.equals("duanOne")) {
			recommendType1 = RecommendType.duan_one;
		} else if (type != null && type.equals("duanTwo")) {
			recommendType1 = RecommendType.duan_two;
		} else if (type != null && type.equals("yunThree")) {
			recommendType1 = RecommendType.yun_third;
		}

		model.addAttribute("page", productService.findPage(productCategory,
				brand, promotion, tags, null, null, null, isMarketable, isList,
				isTop, isGift, isOutOfStock, isStockAlert, OrderType.dateDesc,
				recommendType1, isMiao, isWei, isApp, isJLProduct, isJoin,
				pageable));
		return "/admin/product/selectProduct";
	}

	@RequestMapping(value = "/listProduct", method = RequestMethod.GET)
	public String list(Long productCategoryId, String type, Long id,
			Long brandId, Long promotionId, Long tagId, Boolean isMarketable,
			Boolean isList, Boolean isTop, Boolean isGift,
			Boolean isOutOfStock, Boolean isStockAlert, Boolean isMiao,
			Boolean isWei, Boolean isApp, Boolean isJLProduct, Boolean isJoin,
			Pageable pageable, Long conId, ModelMap model) {
		if (pageable.getSearchProperty()==null) {
			pageable.setSearchProperty("name");
		}
		
		ProductCategory productCategory = productCategoryService
				.find(productCategoryId);
		Brand brand = brandService.find(brandId);
		Promotion promotion = promotionService.find(promotionId);
		List<Tag> tags = tagService.findList(tagId);
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("promotions", promotionService.findAll());
		model.addAttribute("tags", tagService.findList(Type.product));
		model.addAttribute("productCategoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("promotionId", promotionId);
		model.addAttribute("tagId", tagId);
		model.addAttribute("isMarketable", isMarketable);
		model.addAttribute("isList", isList);
		model.addAttribute("isTop", isTop);
		model.addAttribute("type", type);
		model.addAttribute("id", id);
		model.addAttribute("conId", conId);
		model.addAttribute("isGift", isGift);
		model.addAttribute("isOutOfStock", isOutOfStock);
		model.addAttribute("isStockAlert", isStockAlert);
		RecommendType recommendType1 = new Product().getRecommendType();
		if (type != null && type.equals("duanOne")) {
			recommendType1 = RecommendType.duan_one;
		} else if (type != null && type.equals("duanTwo")) {
			recommendType1 = RecommendType.duan_two;
		} else if (type != null && type.equals("yunThree")) {
			recommendType1 = RecommendType.yun_third;
		}
		model.addAttribute("page", productService.findPage(productCategory,
				brand, promotion, tags, null, null, null, isMarketable, isList,
				isTop, isGift, isOutOfStock, isStockAlert, OrderType.dateDesc,
				recommendType1, isMiao, isWei, isApp, isJLProduct, isJoin,
				pageable));
		return "/admin/product/productInfo";
	}

	@RequestMapping(value = "/getProductInfo", method = RequestMethod.POST)
	public @ResponseBody
	List<Product> getProductInfo(Long[] ids, ModelMap model) {
		List<Product> list = productService.findList(ids);
		return list;

	}
	
	@RequestMapping(value = "/check_image", method = RequestMethod.POST)
	public @ResponseBody
	boolean checkImage(Product product) {
		for (Iterator<ProductImage> iterator = product.getProductImages()
				.iterator(); iterator.hasNext();) {
			ProductImage productImage = iterator.next();
			if (productImage == null || productImage.isEmpty()) {
				iterator.remove();
				continue;
			}
			if (productImage.getFile() != null
					&& !productImage.getFile().isEmpty()) {
				if (!fileService
						.isValid(FileType.image, productImage.getFile())) {
					return false;
				}
			}
		}
		return true;
	}
	/**
	 * 组合套包商品列表
	 */
	@RequestMapping(value = "/selectProductDialogOfCombinationType", method = RequestMethod.GET)
	public String selectProductDialogOfCombinationType(String type, Long id,
			Long productCategoryId, Long brandId, Long promotionId, Long tagId,
			Boolean isMarketable, Boolean isList, Boolean isTop,
			Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
			Pageable pageable, ModelMap model) {
		ProductCategory productCategory = productCategoryService
				.find(productCategoryId);
		Brand brand = brandService.find(brandId);
		Promotion promotion = promotionService.find(promotionId);
		List<Tag> tags = tagService.findList(tagId);
		model.addAttribute("type", type);
		model.addAttribute("id", id);
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("promotions", promotionService.findAll());
		model.addAttribute("tags", tagService.findList(Type.product));
		model.addAttribute("productCategoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("promotionId", promotionId);
		model.addAttribute("tagId", tagId);
		model.addAttribute("isMarketable", isMarketable);
		model.addAttribute("isList", isList);
		model.addAttribute("isTop", isTop);
		model.addAttribute("isGift", isGift);
		model.addAttribute("isOutOfStock", isOutOfStock);
		model.addAttribute("isStockAlert", isStockAlert);
	

		model.addAttribute("page", productService.findPage(productCategory,
				brand, promotion, tags, null, null, null, isMarketable, isList,
				isTop, isGift, isOutOfStock, isStockAlert, OrderType.dateDesc,
				null, pageable));
		return "/admin/product/selectProductOfCombinationType";
	}
	
	/**
	 * 组合套包列表
	 */
	@RequestMapping(value = "/listProductOfCombinationType", method = RequestMethod.GET)
	public String listProductOfCombinationType(Long productCategoryId, String type, Long id,
			Long brandId, Long promotionId, Long tagId, Boolean isMarketable,
			Boolean isList, Boolean isTop, Boolean isGift,
			Boolean isOutOfStock, Boolean isStockAlert, Pageable pageable,
			ModelMap model) {
		ProductCategory productCategory = productCategoryService
				.find(productCategoryId);
		Brand brand = brandService.find(brandId);
		Promotion promotion = promotionService.find(promotionId);
		List<Tag> tags = tagService.findList(tagId);
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("promotions", promotionService.findAll());
		model.addAttribute("tags", tagService.findList(Type.product));
		model.addAttribute("productCategoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("promotionId", promotionId);
		model.addAttribute("tagId", tagId);
		model.addAttribute("isMarketable", isMarketable);
		model.addAttribute("isList", isList);
		model.addAttribute("isTop", isTop);
		model.addAttribute("type", type);
		model.addAttribute("id", id);
		model.addAttribute("isGift", isGift);
		model.addAttribute("isOutOfStock", isOutOfStock);
		model.addAttribute("isStockAlert", isStockAlert);
		model.addAttribute("page", productService.findPage(productCategory,
				brand, promotion, tags, null, null, null, isMarketable, isList,
				isTop, isGift, isOutOfStock, isStockAlert, OrderType.dateDesc,
				null, pageable));
		return "/admin/product/productInfoOfCombinationType";
	}
	
	/**
	 * 商品设置
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/setting",method = RequestMethod.GET)
	public Product setting(Long id,ModelMap model){
		Product product = productService.find(id);
		model.addAttribute("product", product);
		return product;
	} 
	/**
	 * 商品设置更新(模版)
	 * @param product
	 * @param isPCShow
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/updateModify", method = RequestMethod.GET)
	@ResponseBody 
	public Product updateModify(Long productId){
		Product oldProduct = productService.find(productId);
		if(oldProduct.getIsTemplate()!=null){
			if(oldProduct.getIsTemplate()){
				oldProduct.setIsTemplate(false);
			}else{
				oldProduct.setIsTemplate(true);
			}
		}
		productService.update(oldProduct);
		return oldProduct;
	}
	
	/**
	 * 商品设置更新(PC显示)
	 * @param productId
	 * @return
	 */
	@RequestMapping(value = "/updateModifyAjax", method = RequestMethod.GET)
	@ResponseBody 
	public Product updateModifyAjax(Long productId){
		Product oldProduct = productService.find(productId);
		if(oldProduct.getIsPCShow()!=null){
			if(oldProduct.getIsPCShow()){
				oldProduct.setIsPCShow(false);
			}else{
				oldProduct.setIsPCShow(true);
			}
		}
		productService.update(oldProduct);
		return oldProduct;
	}
	/**
	 * 复制商品
	 * @param id
	 * @param saveAndPreview
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/copy", method = RequestMethod.GET)
	public String copy(Long id, String saveAndPreview, ModelMap model) {
		model.addAttribute("productCategoryTree",
				productCategoryService.findTree());
		model.put("defaultExpireDate", DateUtil.addDate(new Date(), 1));
		Product product = productService.find(id);
		model.addAttribute("product", product);
		
		model.put("departures", departureService.findAll());
		model.put("destinations",destinationService.findAll());
		
		if (product!=null && product.getPackageProducts()!=null) {
			model.addAttribute("products1", product.getPackageProducts());
			model.addAttribute("products2", product.getPackageProducts());
		}
		model.put("defaultExpireDate", DateUtil.addDate(new Date(), 1));
		model.addAttribute("saveAndPreview", saveAndPreview);
		model.put("defaultBeginDate", new Date());
		model.put("templates", editorTemplateService.findAll());
		return "/admin/product/copy";
	}
	
	/**
	 * 商品设置PC首页轮播展示
	 * @param productId
	 * @return
	 */
	@RequestMapping(value = "/updateCarouselAjax", method = RequestMethod.GET)
	@ResponseBody 
	public Product updateCarouselAjax(Long productId){
		Product oldProduct = productService.find(productId);
		if(oldProduct.getIsCarousel()!=null){
			if(oldProduct.getIsCarousel()){
				oldProduct.setIsCarousel(false);
			}else{
				oldProduct.setIsCarousel(true);
			}
		}
		productService.update(oldProduct);
		return oldProduct;
	}
	/**
	 * 刷新出发地
	 * @return
	 */
	@RequestMapping(value = "/refreshStartAddress", method = RequestMethod.POST)
	@ResponseBody
	public List<Departure> refreshStartAddress(){
		return departureService.findAll();
	}
	/**
	 * 刷新目的地
	 * @return
	 */
	@RequestMapping(value = "/refreshDestination", method = RequestMethod.POST)
	@ResponseBody
	public List<Destination> refreshDestination(){
		return destinationService.findAll();
	}
	
	/**
	 * 刷新商品分类
	 * @return
	 */
	@RequestMapping(value = "/refreshProductCategory",method = RequestMethod.POST)
	@ResponseBody
	public List<ProductCategory> refreshProductCategory(){
		return productCategoryService.findTree();
	}
	
	
	
	@RequestMapping(value = "/stick", method = RequestMethod.GET)
	public String stick(ModelMap model) {
		model.put("products", productService.findStickProduct());
		return "/admin/product/stick";
	}
	
	
	@RequestMapping(value = "/updateStickOrder", method = RequestMethod.GET)
	public String updateStickOrder(ModelMap model,ProductVo productVo) {
		if(productVo!=null&&productVo.getItemVos()!=null&&productVo.getItemVos().size()!=0){
			for(ProductItemVo itemVo:productVo.getItemVos()){
				if(itemVo.getProductId()!=null){
					Product oldProduct=productService.find(itemVo.getProductId());
					oldProduct.setOrder(itemVo.getOrder());
					productService.update(oldProduct);
				}
			}
		}
		return "redirect:list.jhtml";
	}
}